package com.edu.admin.handle;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.edu.admin.enums.ExceptionEnum;
import com.edu.admin.exception.SysException;
import com.edu.admin.common.RestResult;

/**
 * 统一异常处理
 * 
 * @author Wangjiong
 * 
 */
@ControllerAdvice
public class ExceptionHandle {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public RestResult handle(Exception ex) {
    	if (ex instanceof SysException) {
    		SysException sysException = (SysException) ex;
    		logger.error("【标准系统异常】{}", ex.getClass().getName());
            return RestResult.error(sysException.getCode(), sysException.getMessage());
    	}
    	else if (ex instanceof MethodArgumentNotValidException)
        {
        	StringBuilder errorStr = new StringBuilder();
        	MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
        	BindingResult bindingResult = exception.getBindingResult();
        	if(bindingResult.hasErrors())
        	{
        		List<FieldError> fieldErrors = bindingResult.getFieldErrors();
	   			fieldErrors.forEach(fieldError -> {
	   				errorStr.append(fieldError.getDefaultMessage()).append(",");
	                //日志打印不符合校验的字段名和错误提示
	   				logger.error("error field is : {} ,message is : {}", fieldError.getField(), fieldError.getDefaultMessage());
	             });
	   			 
   			 }

        	return RestResult.error(ExceptionEnum.VALIDERROR.getCode(),errorStr.toString());
        }
        else if	(ex instanceof AccessDeniedException)
        {
        	logger.error("【系统异常】{}", ex.getClass().getName());
            return RestResult.error(ExceptionEnum.FORBIDDEN.getCode(), "缺少访问权限，请联系管理员");
        }
        else 
        {
        	logger.error("【未知异常】{}", ex.getClass().getName());
    		return RestResult.error("异常错误");
        }

    }
}
